<?php

namespace frontend\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "member".
 *
 * @property integer $id
 * @property string $tel
 * @property string $token
 * @property string $username
 * @property string $auth_key
 * @property string $auth_key_create_time
 * @property string $password_hash
 * @property string $password_reset_token
 * @property integer $status
 * @property string $email
 * @property string $salt
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $last_login_time
 * @property integer $last_login_ip
 * @property string $openid
 */
class Member extends \yii\db\ActiveRecord implements IdentityInterface
{
    public $password;

    public $confirmPassword;

    public $verifyCode;

    public $messageCode;


    /**
     * 附加行为 系统的行为
     * @return array
     */
    public function behaviors()
    {
        return [
            //给行为命名
            'time'=>[
                //一个行为一个数组
                'class'=>TimestampBehavior::className(),
                'attributes'=>[
                    //插入之前执行的事件
                    ActiveRecord::EVENT_BEFORE_INSERT=>['created_at','updated_at'],
                    //更新之前执行的事件
                    ActiveRecord::EVENT_BEFORE_UPDATE=>['updated_at'],
                ],


            ],
        ];
    }
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'member';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'email','password','confirmPassword'], 'required'],
            [['auth_key_create_time', 'status', 'created_at', 'updated_at', 'last_login_time', 'last_login_ip'], 'integer'],
            [['tel'], 'string', 'max' => 11],
            [['auth_key'], 'string', 'max' => 32],
            [['username', 'password_hash','openid', 'password_reset_token', 'email'], 'string', 'max' => 100],
            [['username'], 'unique'],
            [['email'], 'unique'],
            [['password_reset_token'], 'unique'],
            [['verifyCode'],'captcha'],
            [['password','confirmPassword'],'string','max'=>32],
            [['confirmPassword'],'validateRePassword'],
            [['messageCode'],'validatesmsCode'],
        ];
    }

    public function validatesmsCode()
    {
        $code = Yii::$app->session->get('tel_'.$this->tel);
        if($this->messageCode != $code){
            $this->addError('messageCode','短信验证码输入错误');
        }
    }

    /**
     * @param $attribute
     * @param $params
     * @return void
     */
    public function validateRePassword($attribute, $params){
        //验证错误的情况
//        return $this->password==$this->$attribute;
        if($this->password != $this->$attribute){
            $this->addError($attribute,'确认密码输入不正确');
        }

    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'tel' => '手机号码：',
            'token' => '令牌字符串',
            'username' => '用户名：',
            'auth_key' => '自动登录令牌',
            'auth_key_create_time' => '令牌创建时间',
            'password_hash' => '密码',
            'password_reset_token' => 'Password Reset Token',
            'status' => '状态',
            'email' => '邮箱：',
            'salt' => '盐',
            'created_at' => '注册时间',
            'updated_at' => 'Updated At',
            'last_login_time' => '最后登录事件',
            'last_login_ip' => '最后登录ip',
            'password'=>'密码：',
            'confirmPassword'=>'确认密码：',
            'verifyCode'=>'验证码：',
            'messageCode'=>'短信验证：',
        ];
    }

    /** 登录 */
    public function signup()
    {
        //验证通过后 保存用户的信息
        $this->generatePasswdHash($this->password);
        $this->generateAuth();
        $this->last_login_ip = ip2long(Yii::$app->request->getUserIP());
        $this->last_login_time =time();
        $r = $this->save(false);
        //保存成功后自动登录
        if($r){
            Yii::$app->user->login($this);
        }
        return $r;


    }

    /** 生成hash密码 */
    public function generatePasswdHash($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);

    }
    /** 生成auth */
    public function generateAuth()
    {
        $this->auth_key=Yii::$app->security->generateRandomString();
        $this->auth_key_create_time=time();
    }
    /**
     * Finds an identity by the given ID.
     * @param string|int $id the ID to be looked for
     * @return IdentityInterface the identity object that matches the given ID.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentity($id)
    {
        return Member::findOne(['id'=>$id]);
    }

    /**
     * Finds an identity by the given token.
     * @param mixed $token the token to be looked for
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return IdentityInterface the identity object that matches the given token.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return Member::findOne(['token'=>$token]);
    }

    /**
     * Returns an ID that can uniquely identify a user identity.
     * @return string|int an ID that uniquely identifies a user identity.
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Returns a key that can be used to check the validity of a given identity ID.
     *
     * The key should be unique for each individual user, and should be persistent
     * so that it can be used to check the validity of the user identity.
     *
     * The space of such keys should be big enough to defeat potential identity attacks.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @return string a key that is used to check the validity of a given identity ID.
     * @see validateAuthKey()
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * Validates the given auth key.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @param string $authKey the given auth key
     * @return bool whether the given auth key is valid.
     * @see getAuthKey()
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey()==$authKey;
    }
}
